#!/usr/bin/python

'''
	This is the interface between the HTML form and scripts for the GOODMAN exposure time calculator.
'''

#
# Loading apropriate libraries
#

import sys,os
import cgi
import cgitb
cgitb.enable()

from calcF import * # important definitions for the ITC

os.environ[ 'HOME' ] = '/tmp/'

import matplotlib
matplotlib.use( 'Agg' )
import pylab as py

from optparse import OptionParser
	
parser = OptionParser()
    
parser.add_option('-n','--no-browser',
		  help = 'Run with this option for testing purpose.',action='store_true',default=False)

opt,args = parser.parse_args(sys.argv)

print "Content-type: text/html\n"
print """
<html>
<body>
<h1>ITC4GOODMAN - Results</h1>
<p style="width:500px;"> WARNING: S/N graph only available for "Calculate S/N for specified Total Integration Time" option.</p> 
<p style="width:500px;"> WARNING: If you get a blanck graph with no result (followed by a resulting S/N=0 or NaN) check if you have set the wavelenght
to an apropriate region of the selected configuration. If you get a bunch of debuging code don't PANIC! Write an e-mail
to the SOAR staff with a description of the input that generated the nonsense output and we will try to figure out the problem.
</p>
"""
#<p style="width:500px;"> WARNING: The ITC was calibrated with observations performed prior to the
#upgrades in GOODMAN lens. Overall results should provide inferior limits to S/N. </p>
#"""

#
# Enable debuging messages for cgi (comment this line when the ITC is mature enough)
#
#cgitb.enable() 

#
# Defines the path containing the apropriate scripts, configuration files or else.
#
_path='ITC/'
_tmp='/tmp' #'/home/user/soarcalc/www_lna/tmpfiles'

#
# Input from html form
#
if not opt.no_browser:
	form = cgi.FieldStorage()

#
# This is a template file whith the ETC configuration
#
text_form_fobj = open(os.path.join(_path,'config_template.py'))
text_form = text_form_fobj.read() 
text_form_fobj.close()

#
# Replace input field from webform on the dictionary form_par
#
try:
	for i in form.keys():
#
# form_convert is a dictionary of functions that (should) translate the data types apropriately
#
		form_par[i] = form_convert[i](form[i].value)
except NameError:
	print '<p> [WARNING]: Running in fallback mode. No communication with html form. </p>'

print '''<h1>Input Parameters:</h1>

<table border="1">

'''

tab_def = [3,5]
keys = form_par.keys()

for i in range(tab_def[0]):
	line_str = '<tr>'
	for j in range(tab_def[1]):
		line_str += "<td> %s = %s </td>" % (par_title[ keys[i*tab_def[0]+j]], str(form_par[keys[i*tab_def[0]+j]]))
        	#line_str += "<td> ", par_title[ keys[i*tab_def[0]+j]],' = ',form_par[keys[i*tab_def[0]+j]],'</td>'
	line_str += '</tr>'
	print line_str

print '</table>\n'

#
# Loading parameters to python workspace
#
ex_config =  map(str.strip,str(text_form % form_par).split('\n'))
for i in ex_config:
#	print "<p>", i,'</p>'
	exec i 
choose = form_par['spectype']#.value 
if choose == 'Spiral galaxy':
	spiral='x'                      # Spiral galaxy
	#return 0
elif choose == 'Elliptical galaxy':
	elliptical='x'                  # Eliptical galaxy
	#return 0
elif choose == 'HII Region':
	hiireg='x'                      # HII region
	#return 0
elif choose == 'Planetary Nebulae':
	pn='x'                          # Planetary Nebulae
	#return 0
elif choose == 'Quasar':
	qso='x'                         # Quasar
	#return 0
elif choose == 'Star (LTT3218)':
	star='x'                       # Star (LTT3218)
	#return 0
elif choose == 'Blackbody':
	blackbody='x'                       # Star (LTT3218)
	#return 0


#
# Execute ITC scripts from Sergio 
#
execfile(os.path.join(_path,'snspec.py'))

